import { Response } from 'express';
import { AuthRequest } from '../middleware/auth';
import { NotificationService } from '../services/NotificationService';
import { logger } from '../utils/logger';

export class NotificationController {
  // 获取通知列表
  public getNotifications = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      if (!req.user) {
        res.status(401).json({
          success: false,
          message: '用户认证失败'
        });
        return;
      }

      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 20;
      const unreadOnly = req.query.unreadOnly === 'true';
      const skip = (page - 1) * limit;

      logger.info('获取通知列表请求', { 
        userId: req.user.id, 
        page, 
        limit,
        unreadOnly 
      });

      // 获取通知列表
      const notifications = await NotificationService.getUserNotifications(
        req.user.id,
        limit,
        skip,
        unreadOnly
      );

      // 获取总数
      const { Notification } = await import('../models/Notification');
      const query: any = { recipient: req.user.id };
      if (unreadOnly) {
        query.isRead = false;
      }
      const total = await Notification.countDocuments(query);

      res.json({
        success: true,
        data: {
          notifications,
          pagination: {
            page,
            limit,
            total,
            pages: Math.ceil(total / limit)
          }
        }
      });
    } catch (error: any) {
      logger.error('获取通知列表失败', { 
        userId: req.user?.id,
        error: error.message 
      });

      res.status(500).json({
        success: false,
        message: '获取通知列表失败，请稍后重试'
      });
    }
  };

  // 获取未读通知数量
  public getUnreadCount = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      if (!req.user) {
        res.status(401).json({
          success: false,
          message: '用户认证失败'
        });
        return;
      }

      const count = await NotificationService.getUnreadCount(req.user.id);

      res.json({
        success: true,
        data: {
          count
        }
      });
    } catch (error: any) {
      logger.error('获取未读通知数量失败', { 
        userId: req.user?.id,
        error: error.message 
      });

      res.status(500).json({
        success: false,
        message: '获取未读通知数量失败'
      });
    }
  };

  // 标记通知为已读
  public markAsRead = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      if (!req.user) {
        res.status(401).json({
          success: false,
          message: '用户认证失败'
        });
        return;
      }

      const { id } = req.params;

      const success = await NotificationService.markAsRead(id, req.user.id);

      if (!success) {
        res.status(404).json({
          success: false,
          message: '通知不存在或无权操作'
        });
        return;
      }

      res.json({
        success: true,
        message: '已标记为已读'
      });
    } catch (error: any) {
      logger.error('标记通知已读失败', { 
        userId: req.user?.id,
        notificationId: req.params.id,
        error: error.message 
      });

      res.status(500).json({
        success: false,
        message: '操作失败，请稍后重试'
      });
    }
  };

  // 标记所有通知为已读
  public markAllAsRead = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      if (!req.user) {
        res.status(401).json({
          success: false,
          message: '用户认证失败'
        });
        return;
      }

      await NotificationService.markAllAsRead(req.user.id);

      res.json({
        success: true,
        message: '已标记所有通知为已读'
      });
    } catch (error: any) {
      logger.error('标记所有通知已读失败', { 
        userId: req.user?.id,
        error: error.message 
      });

      res.status(500).json({
        success: false,
        message: '操作失败，请稍后重试'
      });
    }
  };

  // 删除通知
  public deleteNotification = async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      if (!req.user) {
        res.status(401).json({
          success: false,
          message: '用户认证失败'
        });
        return;
      }

      const { id } = req.params;

      const success = await NotificationService.delete(id, req.user.id);

      if (!success) {
        res.status(404).json({
          success: false,
          message: '通知不存在或无权操作'
        });
        return;
      }

      res.json({
        success: true,
        message: '通知已删除'
      });
    } catch (error: any) {
      logger.error('删除通知失败', { 
        userId: req.user?.id,
        notificationId: req.params.id,
        error: error.message 
      });

      res.status(500).json({
        success: false,
        message: '删除失败，请稍后重试'
      });
    }
  };
}